package com.yuan.spring.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author yuaneg 2018/7/18
 */
@Component
@ServerEndpoint(value = "/trans")
public class WebSocketServer {

    private static Session session;

    @OnOpen
    public void onOpen(Session session)  throws Exception{
        WebSocketServer.session = session;
        WebSocketServer.session.getBasicRemote().sendText("服务端发来的消息，连接成功啦。。。。。。。");
        System.out.println("连接成功");
    }

    @OnClose
    public void onClose() {
        System.out.println("关闭啦");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("接收到消息：" + message);
    }

    /**
     * 发送消息方法。
     */
    public static void sendMessage(String message) throws IOException {
            WebSocketServer.session.getBasicRemote().sendText(message);
    }
}
